package com.egene.tw.activity.signs.heart;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.egene.tw.R;
import com.egene.tw.activity.main.MainActivity;
import com.egene.tw.activity.signs.BaseMeasureActivity;
import com.egene.tw.activity.signs.fatigue.FatigueActivity;
import com.egene.tw.blue.BluetoothLeServiceV2;
import com.egene.tw.blue.ShakeUtils;
import com.egene.tw.bus.BusHelper;
import com.egene.tw.bus.LoadDataEndEvent;
import com.egene.tw.bus.MeasureEndEvent;
import com.egene.tw.data.DataRepository;
import com.egene.tw.data.RealmHelper;
import com.egene.tw.data.entity.FatigueData;
import com.egene.tw.data.entity.HeartData;
import com.egene.tw.data.entity.OxygenData;
import com.egene.tw.data.utils.CalUtils;
import com.egene.tw.ui.signs.HeartCenterView;

import org.greenrobot.eventbus.Subscribe;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Function;

@EActivity(R.layout.activity_heart)
public class HeartActivity extends BaseMeasureActivity {
    float MAX_VALUE = 220;

    private int value;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BusHelper.register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusHelper.unRegister(this);
    }

    @ViewById(R.id.viewCenter)
    HeartCenterView viewCenter;

    //ToolBar Views
    @ViewById(R.id.actionBar)
    Toolbar mToolbarView;
    @ViewById(R.id.toolbar_title)
    TextView mToolBarTitle;

    @ViewById(R.id.btnStart)
    TextView btnStart;
    @ViewById(R.id.textValue)
    TextView textValue;

    @ViewById(R.id.textLastTime)
    TextView textLastTime;


    @ViewById(R.id.mRecyclerView)
    RecyclerView mRecyclerView;


    @AfterViews
    void initViews() {
        mToolbarView.setNavigationIcon(R.drawable.ic_back);
        mToolbarView.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        initListView();
        initBle();
        getList();
    }

    @Click(R.id.btnStart)
    void btnStart() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            BluetoothLeServiceV2.connectAuto(this);
            return;
        }
        btnStart.setText(R.string.measureing);
        textValue.setText("0");

        viewCenter.setPercent(0);
        heartRT();
    }


    @Click(R.id.viewBottomDay)
    void viewBottomDay() {
        HeartDetailActivity_.intent(this).type(0).start();
    }

    @Click(R.id.viewBottomWeek)
    void viewBottomWeek() {
        HeartDetailActivity_.intent(this).type(1).start();
    }

    @Click(R.id.viewBottomMonth)
    void viewBottomMonth() {
        HeartDetailActivity_.intent(this).type(2).start();
    }

    @Subscribe
    public void onEvent(LoadDataEndEvent data) {
        getList();
    }

    @Subscribe
    public void onEvent(HeartData data) {
        if (data.getValue() != 0) {
            value = data.getValue();
            textValue.setText("" + value);

            viewCenter.setPercent(value / MAX_VALUE * 100);
        }
    }

    @Subscribe
    public void onEvent(MeasureEndEvent data) {
        btnStart.setText(R.string.start_measure);
        if (value != 0) {
            DataRepository.getInstance()
                    .saveHeartData(System.currentTimeMillis(), value)
                    .flatMap(new Function<Object, ObservableSource<?>>() {
                        @Override
                        public ObservableSource<?> apply(Object o) throws Exception {
                            return DataRepository.getInstance().uploadData();
                        }
                    })
                    .doFinally(new Action() {
                        @Override
                        public void run() throws Exception {
                            getList();
                        }
                    })
                    .subscribe(new Observer<Object>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Object o) {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {
                        }
                    });
        } else {
            getList();
        }
    }


    private void getList() {
        DataRepository.getInstance()
                .heartDataList()
                .subscribe(new Observer<List<HeartData>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(List<HeartData> heartData) {
                        updateUI(heartData);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void updateUI(List<HeartData> list) {
        if (list.size() > 0) {
            HeartData data = list.get(0);
            textValue.setText(data.getValue() + "");

            viewCenter.setPercent(data.getValue() / MAX_VALUE * 100);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            textLastTime.setText(getString(R.string.last_measure_time) + sdf.format(data.getTime()));
        }

        mDatas.clear();
        mDatas.addAll(list);
        mAdapter.notifyDataSetChanged();
    }


    private HomeAdapter mAdapter;
    private List<HeartData> mDatas;

    private void initListView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mDatas = new ArrayList<>();
        mAdapter = new HomeAdapter();
        mRecyclerView.setAdapter(mAdapter);
    }


    class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {

        @Override
        public HomeAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            HomeAdapter.MyViewHolder holder = new HomeAdapter.MyViewHolder(LayoutInflater.from(HeartActivity.this).inflate(R.layout.item_history_record, parent, false));
            return holder;
        }

        @Override
        public void onBindViewHolder(HomeAdapter.MyViewHolder holder, int position) {
            if (position == 0) {
                holder.img.setImageResource(R.drawable.hr_list_icon);
            } else {
                holder.img.setImageResource(R.drawable.fatigue_icon);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            holder.textTime.setText(sdf.format(mDatas.get(position).getTime()));
            holder.textDesc.setText(mDatas.get(position).getValue() + getString(R.string.ci_feng));
        }

        @Override
        public int getItemCount() {
            return mDatas.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            ImageView img;
            TextView textTime;
            TextView textDesc;

            public MyViewHolder(View view) {
                super(view);
                textDesc = (TextView) view.findViewById(R.id.textDesc);
                textTime = (TextView) view.findViewById(R.id.textTime);
                img = (ImageView) view.findViewById(R.id.img);
            }
        }
    }

}
